package com.wangshaoyu.music_player.service;

import com.wangshaoyu.music_player.controller.StudioTrackJsonController.TrackView;
import com.wangshaoyu.music_player.data_object.TrackDo;
import com.wangshaoyu.music_player.repository.RelationRepo;
import com.wangshaoyu.music_player.repository.RelationRepo.TidToCountDo;
import com.wangshaoyu.music_player.repository.TrackRepo;
import com.wangshaoyu.music_player.session_object.UserSO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TrackService {
    private final TrackRepo trackRepo;
    private final RelationRepo relationRepo;

    @Autowired
    public TrackService(TrackRepo trackRepo, RelationRepo relationRepo) {
        this.trackRepo = trackRepo;
        this.relationRepo = relationRepo;
    }

    public List<TrackView> list(UserSO user) {
        List<TrackDo> trackDoList = trackRepo.selectListByUid(user.uid);
        if (trackDoList.isEmpty()) {
            return new ArrayList<>();
        }

        List<Integer> tidList = trackDoList.stream().map(TrackDo::getTid).collect(Collectors.toList());
        List<TidToCountDo> tidToCountDoList = relationRepo.selectCountGroupByTidList(tidList);
        log.debug("selectCountGroupByTidList ：{}", tidToCountDoList);
        Map<Integer, Integer> tidToCountMap = new HashMap<>();
        for (TidToCountDo tidToCountDo : tidToCountDoList) {
            tidToCountMap.put(tidToCountDo.tid, tidToCountDo.count);
        }

        List<TrackView> trackViewList = new ArrayList<>();
        for (TrackDo trackDo : trackDoList) {
            TrackView view = new TrackView();
            view.tid = trackDo.tid;
            view.title = trackDo.title;
            view.count = tidToCountMap.getOrDefault(trackDo.tid, 0);
            trackViewList.add(view);
        }

        return trackViewList;
    }
}
